package mongo

import (
	"context"
	"go2/log"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
)

func FindOneAndUpdate(db_name, table_name string, filter any, update any, opts ...any) *mongo.SingleResult {
	if ret := MongoShell(db_name, table_name, ActionFindOneAndUpdate, filter, update, opts...); ret != nil {
		return ret.Data.(*mongo.SingleResult)
	}

	return nil
}

func FindOne(db_name, table_name string, filter any, opts ...any) *mongo.SingleResult {
	if ret := MongoShell(db_name, table_name, ActionFindOne, filter, nil, opts...); ret != nil {
		return ret.Data.(*mongo.SingleResult)
	}

	return nil
}

func Find(db_name, table_name string, filter any, opts ...any) []map[string]any {

	if ret := MongoShell(db_name, table_name, ActionFind, filter, nil, opts...); ret != nil {
		cursor := ret.Data.(*mongo.Cursor)

		defer cursor.Close(context.Background())

		results := []map[string]any{}

		for cursor.Next(context.Background()) {
			var result map[string]any
			if err := cursor.Decode(&result); err != nil {
				log.Errorf("Find: %s", err)
			} else {
				results = append(results, result)
			}
		}

		return results
	}

	return nil
}

func Find2Raw(db_name, table_name string, filter any, opts ...any) []bson.Raw {

	if ret := MongoShell(db_name, table_name, ActionFind, filter, nil, opts...); ret != nil {
		cursor := ret.Data.(*mongo.Cursor)

		defer cursor.Close(context.Background())

		var results []bson.Raw

		for cursor.Next(context.Background()) {
			results = append(results, cursor.Current)
		}

		return results
	}

	return nil
}

func Distinct(db_name, table_name string, filed_name string, filter any, opts ...any) []any {
	if data_list := MongoShell(db_name, table_name, ActionDistinct, filter, filed_name, opts...); data_list != nil {
		return data_list.Data.([]any)
	}

	return nil
}

func CountDocuments(db_name, table_name string, filter any) int64 {
	if ret := MongoShell(db_name, table_name, ActionCountDocuments, filter, nil); ret != nil {
		return ret.Data.(int64)
	}
	return -1
}
